/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.com.davweb;

import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.Calendar;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.Option;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.event.ValueChangeEvent;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import py.com.domain.Ciudades;
import py.com.domain.Paises;
import py.com.domain.Personas;
import py.com.domain.Profesiones;
import py.com.webdav.util.HibernateUtil;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version RegistroPersona.java
 * @version Created on Apr 28, 2010, 12:06:08 AM
 * @author markos
 */
public class RegistroPersona extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private TextField txtNombreApellido = new TextField();

    public TextField getTxtNombreApellido() {
        return txtNombreApellido;
    }

    public void setTxtNombreApellido(TextField tf) {
        this.txtNombreApellido = tf;
    }
    private Calendar calendar1 = new Calendar();

    public Calendar getCalendar1() {
        return calendar1;
    }

    public void setCalendar1(Calendar c) {
        this.calendar1 = c;
    }
    private TextField txtCI = new TextField();

    public TextField getTxtCI() {
        return txtCI;
    }

    public void setTxtCI(TextField tf) {
        this.txtCI = tf;
    }
    private DropDown dropSexo = new DropDown();

    public DropDown getDropSexo() {
        return dropSexo;
    }

    public void setDropSexo(DropDown dd) {
        this.dropSexo = dd;
    }
    private DropDown dropEstadoCivil = new DropDown();

    public DropDown getDropEstadoCivil() {
        return dropEstadoCivil;
    }

    public void setDropEstadoCivil(DropDown dd) {
        this.dropEstadoCivil = dd;
    }
    private TextField txtTelefono = new TextField();

    public TextField getTxtTelefono() {
        return txtTelefono;
    }

    public void setTxtTelefono(TextField tf) {
        this.txtTelefono = tf;
    }
    private TextField txtDireccion = new TextField();

    public TextField getTxtDireccion() {
        return txtDireccion;
    }

    public void setTxtDireccion(TextField tf) {
        this.txtDireccion = tf;
    }
    private DropDown dropProfesion = new DropDown();

    public DropDown getDropProfesion() {
        return dropProfesion;
    }

    public void setDropProfesion(DropDown dd) {
        this.dropProfesion = dd;
    }
    private DropDown dropPais = new DropDown();

    public DropDown getDropPais() {
        return dropPais;
    }

    public void setDropPais(DropDown dd) {
        this.dropPais = dd;
    }
    private DropDown dropNacionalidad = new DropDown();

    public DropDown getDropNacionalidad() {
        return dropNacionalidad;
    }

    public void setDropNacionalidad(DropDown dd) {
        this.dropNacionalidad = dd;
    }
    private DropDown dropLugar = new DropDown();

    public DropDown getDropLugar() {
        return dropLugar;
    }

    public void setDropLugar(DropDown dd) {
        this.dropLugar = dd;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public RegistroPersona() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("RegistroPersona Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {

        if (getSessionBean1().getPersona() != null) {
            Personas p;
            try {
                Session s = HibernateUtil.getSessionFactory().getCurrentSession();
                Transaction t = s.beginTransaction();
                p = (Personas) s.merge(getSessionBean1().getPersona());
                txtCI.setText(p.getDnCedula());
                if (p.getDnDireccion() != null) {
                    txtDireccion.setText(p.getDnDireccion().toString());
                }
                
                if (p.getDnApellidoNombre() != null) {
                    txtNombreApellido.setText(p.getDnApellidoNombre());
                }

                txtTelefono.setText(p.getDnTelefono());
                dropEstadoCivil.setSelected(p.getDnEstadoCivil());
                if (p.getDnLugarNacimiento() != null) {
                    dropLugar.setSelected(p.getDnLugarNacimiento().getCiCiudad().toString());
                }
                if (p.getDnNacionalidad() != null) {
                    dropNacionalidad.setSelected(p.getDnNacionalidad().getPaPais().toString());
                }
                if (p.getDnPaisOrigen() != null) {
                    dropPais.setSelected(p.getDnPaisOrigen().getPaPais().toString());
                }
                if (p.getDnProfesion() != null) {
                    dropProfesion.setSelected(p.getDnProfesion().getPrProfesion().toString());
                }

                dropSexo.setSelected(p.getDnSexo());

                calendar1.setSelectedDate(p.getDnFechaNacimiento());
                t.commit();
            } catch (Exception e) {

                e.printStackTrace();
            }
        } else if(!ajaxProcessing){
            txtCI.setText(null);
            txtDireccion.setText(null);
            txtNombreApellido.setText(null);
            txtTelefono.setText(null);
            dropEstadoCivil.setSelected(null);
            dropLugar.setSelected(null);
            dropNacionalidad.setSelected(null);
            dropPais.setSelected(null);
            dropProfesion.setSelected(null);
            dropSexo.setSelected(null);
            calendar1.setSelectedDate(null);
        }
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public String btnCancel_action() {
        getSessionBean1().setPersona(null);
        return "persona_cancel";
    }
    private Option[] listaSexo = {new Option("M", "Masculino"), new Option("F", "Femenino")};
    private Option[] listaEstadoCivil = {new Option("C", "Casado/a"), new Option("S", "Soltero/a"), new Option("D", "Divorciado/a")};
    private List<Ciudades> listaCiudades;
    private List<Option> listaCiudadesOption;
    private List<Paises> listaPais;
    private List<Option> listaPaisOption;
    private List<Paises> listaNacionalidad;
    private List<Option> listaNacionalidadOption;
    private List<Profesiones> listaProfesion;
    private List<Option> listaProfesionOption;

    public List<Ciudades> getListaCiudades() {
        return listaCiudades;
    }

    public List<Option> getListaCiudadesOption() {
        listaCiudades = new ArrayList<Ciudades>();
        try {
            Session s = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction t = s.beginTransaction();
            Query q = s.createQuery("from Ciudades");
            listaCiudades = q.list();
            listaCiudadesOption = new ArrayList<Option>();
            for (Ciudades ciudades : listaCiudades) {
                listaCiudadesOption.add(new Option(ciudades.getCiCiudad().toString(), ciudades.getCiDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listaCiudadesOption;
    }

    public void setListaCiudadesOption(List<Option> listaCiudadesOption) {
        this.listaCiudadesOption = listaCiudadesOption;
    }

    public List<Option> getListaNacionalidadOption() {
        listaNacionalidad = new ArrayList<Paises>();
        try {
            Session s = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction t = s.beginTransaction();
            Query q = s.createQuery("from Paises");
            listaNacionalidad = q.list();
            listaNacionalidadOption = new ArrayList<Option>();
            for (Paises p : listaNacionalidad) {
                listaNacionalidadOption.add(new Option(p.getPaPais().toString(), p.getPaDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listaNacionalidadOption;
    }

    public void setListaNacionalidadOption(List<Option> listaNacionalidadOption) {
        this.listaNacionalidadOption = listaNacionalidadOption;
    }

    public List<Option> getListaPaisOption() {
        listaPais = new ArrayList<Paises>();
        try {
            Session s = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction t = s.beginTransaction();
            Query q = s.createQuery("from Paises");
            listaPais = q.list();
            listaPaisOption = new ArrayList<Option>();
            for (Paises p : listaPais) {
                listaPaisOption.add(new Option(p.getPaPais().toString(), p.getPaDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return listaPaisOption;
    }

    public void setListaPaisOption(List<Option> listaPaisOption) {
        this.listaPaisOption = listaPaisOption;
    }

    public List<Option> getListaProfesionOption() {
        listaProfesion = new ArrayList<Profesiones>();
        try {

            Session s = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction t = s.beginTransaction();
            Query q = s.createQuery("from Profesiones");
            listaProfesion = q.list();
            listaProfesionOption = new ArrayList<Option>();
            for (Profesiones p : listaProfesion) {
                listaProfesionOption.add(new Option(p.getPrProfesion().toString(), p.getPrDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return listaProfesionOption;
    }

    public void setListaProfesionOption(List<Option> listaProfesionOption) {
        this.listaProfesionOption = listaProfesionOption;
    }

    public void setListaCiudades(List<Ciudades> listaCiudades) {
        this.listaCiudades = listaCiudades;
    }

    public List<Paises> getListaNacionalidad() {
        return listaNacionalidad;
    }

    public void setListaNacionalidad(List<Paises> listaNacionalidad) {
        this.listaNacionalidad = listaNacionalidad;
    }

    public List<Paises> getListaPais() {
        return listaPais;
    }

    public void setListaPais(List<Paises> listaPais) {
        this.listaPais = listaPais;
    }

    public List<Profesiones> getListaProfesion() {
        return listaProfesion;
    }

    public void setListaProfesion(List<Profesiones> listaProfesion) {
        this.listaProfesion = listaProfesion;
    }

    public Option[] getListaSexo() {
        return listaSexo;
    }

    public void setListaSexo(Option[] listaSexo) {
        this.listaSexo = listaSexo;
    }

    public Option[] getListaEstadoCivil() {
        return listaEstadoCivil;
    }

    public void setListaEstadoCivil(Option[] listaEstadoCivil) {
        this.listaEstadoCivil = listaEstadoCivil;
    }

    public String btnOk_action() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tran = session.beginTransaction();
        try {

            Personas p;
            if (getSessionBean1().getPersona() == null) {
                p = new Personas();
            } else {
                p = getSessionBean1().getPersona();
            }
            p.setDnApellidoNombre(txtNombreApellido.getText().toString());
            if (txtCI.getText() != null) {
                p.setDnCedula(Integer.parseInt(txtCI.getText().toString()));
            }
            if (txtDireccion.getText() != null) {
                p.setDnDireccion(txtDireccion.getText().toString());
            }
            if (dropEstadoCivil.getSelected() != null) {
                p.setDnEstadoCivil(dropEstadoCivil.getSelected().toString());
            }

            p.setDnFechaNacimiento(calendar1.getSelectedDate());

            p.setDnLugarNacimiento((Ciudades) session.load(Ciudades.class, Integer.parseInt(dropLugar.getSelected().toString())));
            p.setDnNacionalidad((Paises) session.load(Paises.class, Integer.parseInt(dropNacionalidad.getSelected().toString())));
            p.setDnPaisOrigen((Paises) session.load(Paises.class, Integer.parseInt(dropPais.getSelected().toString())));
            p.setDnProfesion((Profesiones) session.load(Profesiones.class, Integer.parseInt(dropProfesion.getSelected().toString())));
            p.setDnSexo(dropSexo.getSelected().toString().toCharArray()[0]);
            if (txtTelefono.getText() != null) {
                p.setDnTelefono(txtTelefono.getText().toString());
            }
            if (getSessionBean1().getPersona() == null) {
                session.save(p);
            } else {
                session.merge(p);
            }
            tran.commit();
            getSessionBean1().setPersona(null);
            return "success";

        } catch (Exception e) {
            getSessionBean1().setPersona(null);
            tran.rollback();
            e.printStackTrace();
            return "persona_fail";
        }
    }
    
    private boolean ajaxProcessing = false;
    
    public void calendar1_processValueChange(ValueChangeEvent event) {
        long fechaActual = System.currentTimeMillis();
        Date edad = new Date(fechaActual);
        java.util.Calendar cNacimiento = java.util.Calendar.getInstance();
        java.util.Calendar cActual = java.util.Calendar.getInstance();

        cNacimiento.setTime(calendar1.getSelectedDate());
        cActual.setTime(edad);
        ajaxProcessing = true;
    }
}

